<template>
  <div class="search-page">
    <div class="container">
      <div class="search-header">
        <div class="search-form">
          <el-input
            v-model="keyword"
            placeholder="搜索内容..."
            prefix-icon="Search"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">搜索</el-button>
            </template>
          </el-input>
        </div>
        <div class="search-info" v-if="keyword">
          <span>关键词：<strong>{{ keyword }}</strong></span>
          <span>找到 {{ total }} 个相关结果</span>
        </div>
      </div>

      <!-- 搜索结果列表 -->
      <div class="search-results" v-if="results.length > 0">
        <div 
          v-for="item in results" 
          :key="item.id" 
          class="result-item card" 
          @click="goToDetail(item.id)">
          <div class="result-main">
            <div class="result-info">
              <h3 class="result-title" v-html="highlightKeyword(item.title)"></h3>
              <p class="result-summary" v-html="highlightKeyword(item.summary)"></p>
              <div class="result-meta">
                <span class="category-tag">{{ getCategoryName(item.categoryId) }}</span>
                <span class="author">
                  <el-avatar :size="20" :src="item.avatar || userAvatar"></el-avatar>
                  {{ item.nickName }}
                </span>
                <span><el-icon><View /></el-icon> {{ item.views }}</span>
                <span><el-icon><Star /></el-icon> {{ item.likes }}</span>
              </div>
            </div>
            <div class="result-cover" v-if="item.img && isValidImage(item.img)">
              <img :src="item.img" :alt="item.title" @error="handleImageError">
            </div>
          </div>
        </div>
      </div>

      <!-- 无数据 -->
      <div class="no-data card" v-else-if="hasSearched">
        <el-empty description="没有找到相关内容">
          <template #description>
            <p>没有找到与"{{ keyword }}"相关的内容</p>
            <p class="search-tips">
              建议：
              <ul>
                <li>请检查关键词是否有误</li>
                <li>尝试使用其他关键词</li>
                <li>使用更简短的关键词</li>
              </ul>
            </p>
          </template>
        </el-empty>
      </div>
      
      <!-- 暂未搜索 -->
      <div class="no-search card" v-else>
        <div class="search-placeholder">
          <el-icon :size="50" class="search-icon"><Search /></el-icon>
          <p>请输入关键词进行搜索</p>
        </div>
        <div class="hot-search">
          <h3>热门搜索</h3>
          <div class="hot-tags">
            <span v-for="(tag, index) in hotSearchTags" :key="index" class="hot-tag" @click="applyHotSearch(tag)">
              {{ tag.keyword }}
            </span>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-section" v-if="results.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Search, View,Star } from '@element-plus/icons-vue'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()

// 数据状态
const userAvatar = ref('https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png')
const keyword = ref('')
const hasSearched = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const results = ref([])
const hotSearchTags = ref([])

const categories = ref([
  { id: 1, name: '科技' },
  { id: 2, name: '娱乐' },
  { id: 3, name: '体育' },
  { id: 4, name: '国际' },
  { id: 5, name: '财经' },
  { id: 6, name: '教育' },
  { id: 7, name: '文化' },
  { id: 8, name: '动漫' }
])

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await request.get('/hotSearches/list')
    
    if (res.data.code === '200') {
      hotSearchTags.value = res.data.data || []
    } else {
      console.error('获取分类列表失败:', res.data.msg)

    }
  } catch (error) {
    console.error('获取分类列表出错:', error)
  }
}

// 生命周期钩子
onMounted(() => {
  fetchCategories()
  // 从URL获取搜索关键词
  const query = route.query
  if (query.keyword) {
    keyword.value = query.keyword
    search()
  }
})

// 方法
const handleSearch = () => {
  // 更新URL
  if (keyword.value.trim()) {
    router.push({
      path: '/search',
      query: { keyword: keyword.value }
    })
  } else {
    router.push({
      path: '/search'
    })
  }
  
  search()
}

const search = async () => {
  hasSearched.value = true
  
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    }
    
    // 只有在有关键词时才添加title参数
    if (keyword.value.trim()) {
      params.title = keyword.value
    }else {
      params.title = ''
    }
    
    const res = await request.get('/articles/search/page', { params })
    
    if (res.data.code === '200') {
      results.value = res.data.data.records || []
      total.value = res.data.data.total || 0
    } else {
      console.error('搜索失败:', res.data.msg)
    }
  } catch (error) {
    console.error('搜索出错:', error)
  }
}

const getCategoryName = (id) => {
  const category = categories.value.find(item => item.id === id)
  return category ? category.name : '未分类'
}

const goToDetail = (id) => {
  router.push(`/detail/${id}`)
}

const handlePageChange = (page) => {
  currentPage.value = page
  search()
  window.scrollTo(0, 0)
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  search()
  window.scrollTo(0, 0)
}

const highlightKeyword = (text) => {
  if (!keyword.value || !text) return text
  
  // 转义正则表达式中的特殊字符
  const escapeRegExp = (string) => {
    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
  }
  
  const regex = new RegExp(escapeRegExp(keyword.value), 'gi')
  return text.replace(regex, match => `<span class="highlight">${match}</span>`)
}

const applyHotSearch = (tag) => {
  keyword.value = tag.keyword
  handleSearch()
}

const isValidImage = (url) => {
  return url && url.trim() !== ''
}

const handleImageError = (e) => {
  e.target.style.display = 'none'
}
</script>

<style scoped>
.search-page {
  padding: 20px 0 40px;
}

.search-header {
  margin-bottom: 20px;
}

.search-form {
  max-width: 600px;
  margin: 0 auto 20px;
}

.search-info {
  display: flex;
  justify-content: space-between;
  color: #666;
  font-size: 14px;
  max-width: 600px;
  margin: 0 auto;
}

.search-results {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 30px;
}

.result-item {
  padding: 20px;
  cursor: pointer;
}

.result-main {
  display: flex;
  gap: 20px;
}

.result-info {
  flex: 1;
}

.result-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
}

.result-summary {
  color: #666;
  margin-bottom: 15px;
  line-height: 1.6;
}

.result-meta {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  font-size: 13px;
  color: #999;
}

.result-meta > span {
  display: flex;
  align-items: center;
  margin-right: 15px;
  margin-bottom: 5px;
}

.result-meta .el-icon {
  margin-right: 5px;
}

.category-tag {
  background-color: #f4f4f5;
  color: #909399;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.author {
  display: flex;
  align-items: center;
  gap: 5px;
}

.result-cover {
  width: 180px;
  height: 120px;
  flex-shrink: 0;
  overflow: hidden;
  border-radius: 4px;
}

.result-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.result-item:hover .result-cover img {
  transform: scale(1.05);
}

.no-data, .no-search {
  padding: 40px 20px;
  text-align: center;
}

.search-tips {
  font-size: 14px;
  color: #666;
  margin-top: 10px;
}

.search-tips ul {
  display: inline-block;
  text-align: left;
  margin-top: 5px;
}

.search-placeholder {
  margin-bottom: 30px;
}

.search-icon {
  color: #909399;
  margin-bottom: 15px;
}

.hot-search {
  max-width: 600px;
  margin: 0 auto;
}

.hot-search h3 {
  font-size: 16px;
  margin-bottom: 15px;
  color: #333;
}

.hot-tags {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 10px;
}

.hot-tag {
  background-color: #f5f7fa;
  color: #606266;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.hot-tag:hover {
  background-color: #ecf5ff;
  color: #409eff;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

:deep(.highlight) {
  color: #409eff;
  font-weight: bold;
}

@media screen and (max-width: 768px) {
  .result-main {
    flex-direction: column;
  }
  
  .result-cover {
    width: 100%;
    height: 180px;
    margin-top: 10px;
  }
}
</style> 